package com.uwo.house.service.serviceImpl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.uwo.house.beans.PayLogEntity;
import com.uwo.house.dao.AliPayDao;
import com.uwo.house.service.IAliPayService;
import com.uwo.house.util.AliPayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by dell on 2017/10/31.
 */
@Service
public class AliPayService implements IAliPayService {

    //获得初始化的AlipayClient
    private static AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APPID,
            AliPayConfig.APP_PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);

    @Autowired
    AliPayDao aliPayDao;

    public PayLogEntity getPayLogByOrderNo(String orderId) {
        return aliPayDao.getPayLogByOrderNo(orderId);
    }

    /**
     * 电脑付款
     *
     * @param out_trade_no 商户订单号，商户网站订单系统中唯一订单号，必填
     * @param total_amount 付款金额，必填
     * @param subject      订单名称，必填
     * @param body         商品描述，可空
     * @return
     */
    public void trade_computer_pay(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String out_trade_no, String total_amount, String subject, String body) {
        try {
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setNotifyUrl("http://122.237.100.110:80/uwo-house/alipay/alipaynotifyurl");
            alipayRequest.setReturnUrl("http://www.lanhangf.com/center.html");

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    //销售产品码，与支付宝签约的产品码名称。 注：目前仅支持FAST_INSTANT_TRADE_PAY
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            httpResponse.setContentType("text/html;charset=" + AliPayConfig.CHARSET);
            httpResponse.getWriter().write(result);//直接将完整的表单html输出到页面
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (Exception e) {
//            logger.error("内部异常：{}",e.getMessage());
            e.printStackTrace();
        }
    }

    public void updatePayLog(PayLogEntity payLogEntity){
        aliPayDao.updatePayLog(payLogEntity);
    }
}
